// 远端oauth2服务器uri
const GLOBAL_remoteOauth2ServerLoginUri = "http://127.0.0.1:8082/oauth/authorize";
const GLOBAL_remoteOauth2ServerGetCodeUri = "http://127.0.0.1:8082/oauth/authorize";
const GLOBAL_remoteOauth2ServerGetTokenUri = "http://127.0.0.1:8082/oauth/token";

// 当前客户端重定向url
const GLOBAL_localRedirectUrl = "http://127.0.0.1:8080/redirect";

/**
 * 通用: oauth2登录
 *
 * 给出message框, 等待3s后转向oauth2服务器认证界面
 *
 * @param component
 * @param clientId
 * @param redirectUri
 */
const oauth2Login = function (component, clientId, redirectUri) {
    let nextUri = GLOBAL_remoteOauth2ServerLoginUri + "?" + "client_id=" + clientId +
        "&" + "redirect_uri=" + redirectUri + "&" + "response_type=" + "code";

    component.$message({
        message: '登录过期请重新登录',
        type: 'warning',
        onClose: () => {
            window.location.href = nextUri;
        },
    });
}

/**
 * 通用：oauth2获取code
 *
 * 用户同意授权后进行
 *
 * @param component
 * @param clientId
 * @param redirectUri
 */
const oauth2GetCode = function (component, clientId, redirectUri) {
    let postData = {
        'client_id' : clientId,
        'redirect_uri' : redirectUri,
        'response_type' : 'code',
    };

    component.axios({
        method: 'post',
        url: GLOBAL_remoteOauth2ServerGetCodeUri,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        // responseType: 'json',
        data: JSON.stringify(postData)
    })
        .then(function (response) {
            let pData = response.data;
            console.log(pData);
            if (pData.state === 'SUCCESS') {        //重定向
                window.location.href = pData.redirect_uri + "?" + "code=" + pData.code + "&state=getToken";
            } else {
                component.returnInfo = pData.message;
            }
        })
        .catch(function (error) {
            console.log(error);
        })
}

/**
 * 通用：oauth2获取token,
 *
 * grant_type = authorization_code
 *
 * @param component
 * @param code
 * @param redirectUri
 */
const oauth2GetToken = function (component, code, redirectUri) {
    let postData = {
        'grant_type' : "authorization_code",
        'redirect_uri' : redirectUri,
        'code' : code,
    };

    component.axios({
        method: 'post',
        url: GLOBAL_remoteOauth2ServerGetTokenUri,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        // responseType: 'json',
        data: JSON.stringify(postData)
    })
        .then(function (response) {
            let pData = response.data;
            console.log(pData);
            if (pData.state === 'SUCCESS') {        //重定向
                window.location.href = redirectUri + "?" + "access_token=" +
                    pData.access_token + "&refresh_token=" + pData.refresh_token + "&state=gotoResource";
            } else {
                component.returnInfo = pData.message;
            }
        })
        .catch(function (error) {
            console.log(error);
        })
}

/**
 * 通用：oauth2刷新token
 * @param component
 * @param token
 */
const oauth2RefreshToken = function (component, token) {
    let postData = {
        'grant_type' : "refresh_token",
        'code' : token,
    };

    component.axios({
        method: 'post',
        url: GLOBAL_remoteOauth2ServerGetTokenUri,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        // responseType: 'json',
        data: JSON.stringify(postData)
    })
        .then(function (response) {
            let pData = response.data;
            console.log(pData);
            if (pData.state === 'SUCCESS') {        //重定向
                window.location.href = GLOBAL_localRedirectUrl + "?" + "access_token=" +
                    pData.access_token + "&refresh_token=" + pData.refresh_token + "&state=gotoResource";
            } else {    //走用户认证
                window.location.href = GLOBAL_localRedirectUrl + "?" + "state=login";
            }
        })
        .catch(function (error) {
            console.log(error);
        })
}

/**
 * 测试: oauth2客户端
 * @param component
 */
const oauth2LoginTestClient = function (component) {
    oauth2Login(component, "testClient", "http://127.0.0.1:8080/redirect");
}

/**
 * 获取code
 * @param component
 */
const oauth2GetCodeTestClient = function (component) {
    oauth2GetCode(component, "testClient", "http://127.0.0.1:8080/redirect");
}

/**
 * 获取token
 * @param component
 * @param code
 */
const oauth2GetTokenTestClient = function (component, code) {
    oauth2GetToken(component, code, "http://127.0.0.1:8080/redirect");
}

/**
 * 刷新token
 * @param component
 * @param token
 */
const oauth2RefreshTokenTestClient = function (component, token) {
    oauth2RefreshToken(component, token);
}

/**
 * 从资源服务器获取资源
 *
 * @param component 组件
 * @param postUrl post 地址
 * @param data post数据(资源服务器url)
 * @param needAuth 是否要认证
 * @param verifySuccessHandler(component, respData) 验证成功回调
 * @param verifyFailHandler(component, respData) 验证失败回调
 * @param otherFailHandler(component, respData) 其他失败回调
 */
const getDataFromResourceServer = function (component, postUrl, data,
                                            needAuth, verifySuccessHandler, verifyFailHandler, otherFailHandler) {
    let headers = {
        'Content-Type': 'application/json',
    }

    // 如果需要认证, 则准备token
    if (needAuth === true) {
        headers['Cus-Auth2-Token'] = (component.$cookies.get("Cus-Auth2-AccessToken") === null) ? "" : component.$cookies.get("Cus-Auth2-AccessToken");
    }
    // 记录获取资源的路径
    component.$cookies.set("Resource-Uri",window.location.href,"9h","/",'127.0.0.1');

    component.axios({
        method: 'post',
        url: postUrl,
        // responseType: 'json',
        headers: headers,
        data: JSON.stringify(data)
    })
        .then(function (response) {
            let pData = response.data;
            console.log(pData);
            if (pData.state === "SUCCESS") {
                //verifySuccessHandler(component, pData);
                alert("成功获取数据");
            } else {
                alert("失败获取数据,需要重认证");
                window.location.href = GLOBAL_localRedirectUrl + "?" + "state=refreshToken";
            }
        })
        .catch(function (error) {
            console.log(error);
        })
};

/**
 * 重定向至登录, OAuth2, 验证失败回调函数 Cms的
 * @param component
 * @param data
 * @param resourceUrl
 */
const verifyFailRedirectOAuth2LoginHandler_Cms = function (component, data, resourceUrl) {
    component.$message({
        message: '登录过期请重新登录',
        type: 'warning',
        onClose: () => {
            window.location.href = "http://106.54.235.74:8082/authorization/login?clientName=cms" +
                "&redirectUrl=http://127.0.0.1:8080/redirect" +
                "&resourceUrl=" + resourceUrl;
        },
    });
}

/**
 * 重定向至登录, OAuth2, 验证失败回调函数 JudgeSystem的
 * @param component
 * @param data
 * @param resourceUrl
 */
const verifyFailRedirectOAuth2LoginHandler_JudgeSystem = function (component, data, resourceUrl) {
    component.$message({
        message: '登录过期请重新登录',
        type: 'warning',
        onClose: () => {
            window.location.href = "http://106.54.235.74:8082/authorization/login?clientName=judgesystem" +
                "&redirectUrl=http://127.0.0.1:8080/redirect" +
                "&resourceUrl=" + resourceUrl;
        },
    });
}

/**
 * 验证失败回调函数, 仅提醒
 * @param component
 * @param data
 * @param resourceUrl
 */
const verifyFailNoticeHandler = function (component, data, resourceUrl) {
    component.$message({
        message: '登录过期请重新登录, 请新增标签页面, 地址填当前页面',
        type: 'warning'
    });
}

/**
 * 空白的其他失败回调函数
 * @param component
 * @param data
 */
const otherFailBlankHandler = function (component, data) {
    console.log("other fail" + data.errorInfo);
}

/**
 * 空白的验证成功回调函数
 * @param component
 * @param data
 */
const verifySuccessBlankHandler = function (component, data) {
}

export default {
    // old
    getDataFromResourceServer,
    verifyFailRedirectOAuth2LoginHandler_Cms,
    verifyFailRedirectOAuth2LoginHandler_JudgeSystem,
    otherFailBlankHandler,
    verifySuccessBlankHandler,
    verifyFailNoticeHandler,

    // new
    oauth2LoginTestClient,
    oauth2GetCodeTestClient,
    oauth2GetTokenTestClient,
    oauth2RefreshTokenTestClient,
}
